package com.aohe.youzi.activity.main;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.aohe.youzi.Constants;
import com.aohe.youzi.R;
import com.aohe.youzi.databinding.ActivityMainBinding;
import com.aohe.youzi.fragment.home.HomeFragment;
import com.aohe.youzi.fragment.mine.MineFragment;
import com.aohe.youzi.mvp.UnBaseMvpActivity;
import com.aohe.youzi.utils.FastJsonUtil;
import com.aohe.youzi.utils.PreferencesUtil;
import com.aohe.youzi.utils.ToastUtil;
import com.aohe.youzi.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flyn.ScreenUtils;

/**
 * @Auther : ftang
 * @date : 2022/5/20 10:08
 * @describe : 主界面
 */
public class MainActivity extends UnBaseMvpActivity<MainPresenter> implements MainContract {
    private String TAG = getClass().getSimpleName();

    private int index = 0;
    private Activity activity;
    private ActivityMainBinding binding;
    private List<Fragment> fragments = new ArrayList<>();
    public FragmentManager manager = getSupportFragmentManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View rootView = binding.getRoot();
        setContentView(rootView);
        activity = this;
        ScreenUtils.setStatusBarTransparentAndWordsGray(getWindow());
        Log.e(TAG, "MANUFACTURER=" + Build.MANUFACTURER);
        fragments.add(new HomeFragment());
        fragments.add(new MineFragment());
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.container, fragments.get(0));
        transaction.commitAllowingStateLoss();

        binding.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_home:
                        index = 0;
                        changeFragment(0);
                        break;
                    case R.id.rb_mine:
                        index = 1;
                        changeFragment(1);
                        break;
                }
            }
        });

    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (index == 1) {//task界面会获取任务数量,这里无需获取
            return;
        }
    }
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }
    private void changeFragment(int index) {
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.container, fragments.get(index));
        transaction.commitAllowingStateLoss();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @NonNull
    @Override
    public MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    public void showVersionDta(Version version) {
        try {
            PreferencesUtil.putString(activity, "Version", FastJsonUtil.createJsonString(version));
            String versionCode = version.getCode();
            if (versionCode.contains(".")) {
                versionCode = versionCode.replace(".", "");
            }

            String versionName = Utils.getVersionName(activity);
            if (versionName.contains(".")) {
                versionName = versionName.replace(".", "");
            }

            int newCode = Integer.parseInt(versionCode);
            int curCode = Integer.parseInt(versionName);

            if (newCode > curCode) {//有新版本
                getPresenter().getApk(Constants.baseUrl + version.getUrl());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    File apkfile;

    @Override
    public void setApkFile(File file) {
        apkfile = file;
        installApk();
    }

    //7.在请求安装未知应用来源的权限后
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 10086) {

            Uri packageURI = Uri.parse("package:com.aohe.youzi");
//            Uri packageURI = Uri.parse("package:" + getPackageName());
            Log.e(TAG, "packageURI:" + packageURI);
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
            startActivityForResult(intent, 457);
        }
    }

    //8.在 startActivityForResult(intent,457);执行后
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 457) {
            if (Build.VERSION.SDK_INT >= 26) {
                if (getPackageManager().canRequestPackageInstalls()) {

                    installApk();
                } else {
                    ToastUtil.showToast("Installation permission is not enabled, installation failed!");
                }
            }
        }
    }

    //9.安装apk，适配android 7.0
    private void installApk() {
        if (apkfile == null) {
            Log.e(TAG, "1apkfile==null");
            apkfile = new File(getExternalCacheDir().getPath(), "opene.apk");
            Log.e(TAG, "apkfile:" + apkfile.getPath());
        }

        if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(this, "com.aohe.youzi.fileprovider", apkfile);
            Log.e(TAG, "apkUri:" + apkUri);
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(install);
        }
    }

}